package ruifeng.zcj.communcationring.ui;

import android.app.Activity;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.webkit.WebView;

import com.easemob.EMCallBack;
import com.easemob.EMError;
import com.easemob.chat.EMChatManager;
import com.easemob.exceptions.EaseMobException;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import ruifeng.zcj.communcationring.base.base_web_activity.WebViewActivity;
import ruifeng.zcj.communcationring.base.base_web_activity.other.JS;
import ruifeng.zcj.communcationring.groble.FragmentArgs;
import ruifeng.zcj.communcationring.ui.circle.CircleFragment;
import ruifeng.zcj.communcationring.ui.circle.other.CircleJS;
import ruifeng.zcj.communcationring.ui.main.bean.User;

/**
 * Created by Administrator on 2016/9/8 0008.
 */
public class LoginRegisterActivity extends WebViewActivity {

    public static void launch(Activity activity,
                              Class<? extends Fragment> clazz,
                              FragmentArgs args) {
        Intent intent = new Intent(activity, LoginRegisterActivity.class);
        intent.putExtra(KEY_CLASS_NAME, clazz.getName());
        if (args != null) {
            intent.putExtra(KEY_ARGS, args);
        }
        activity.startActivity(intent);
    }

    String url = "http://jj.57810.mom/index.php/PostUpload/checkAccount";
    private HttpUtils httpUtils;


    @Override
    public void initView() {
        String className = getIntent().getStringExtra(KEY_CLASS_NAME);
        if (TextUtils.isEmpty(className)) {
            finish();
            return;
        }
        FragmentArgs values = (FragmentArgs) getIntent().getSerializableExtra(KEY_ARGS);
        MyURL = (String) values.get(CircleFragment.FILM_URL);

        super.initView();
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        mWebview = view;
        //将过滤到的url加入历史栈中
        return true;
    }

    // 是否调用js代码默认是传递
    @Override
    protected boolean isAddJavascriptInterface() {
        return true;
    }

    // new一个子类
    @Override
    public JS newJsObj() {// 传递一个子类给
        CircleJS aa = new CircleJS();
        aa.jsona = "zcj";
        return aa;
    }

    // 一个key
    @Override
    public String HTMLkey() {// 获取他的key
        return "login";
    }

    User mUser = null;

    public void pay(String arg) {
        mUser = User.parasjson(arg);
        if (mUser != null) {
            if (mUser.getMethod().equals("login")) {
                login(arg);

            } else if (mUser.getMethod().equals("register")) {
                login(arg);
            }
        }
    }

    public void finishActivity() {
        LoginRegisterActivity.this.finish();
    }


    @Override
    protected void onPause() {
        super.onPause();
        if (mWebview != null) {
            mWebview.removeAllViews();
            mWebview.destroy();
        }
    }

    /***
     * 用户登录
     **/
    public void login(String mUser) {
        httpUtils = new HttpUtils();
        RequestParams paras = new RequestParams();
        paras.addBodyParameter("json", mUser);


        httpUtils.send(HttpRequest.HttpMethod.POST, url, paras,
                new RequestCallBack<String>() {
                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                        // Toast.makeText(getApplicationContext(), "错误", Toast.LENGTH_SHORT).show();



                    }

                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                        super.onLoading(total, current, isUploading);
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseinfo) {
//                        Logger.d("zcj成功"+responseinfo.result);
//                        button3.setText("成功："+responseinfo.result);
                        register();// 调用环信
                        if (mWebview != null){
                            mWebview.reload();
                        }
                    }
                });
    }

    /***
     * 用户注册环信注册一遍
     **/
    public void register() {
        new Thread(new Runnable() {
            public void run() {
                try {
                    // 调用sdk注册方法
                    if (mUser != null) {
                        String aa = mUser.getUsername();
                        EMChatManager.getInstance().createAccountOnServer(mUser.getUsername(), mUser.getPassword());
                    }
                } catch (final EaseMobException e) {
                    int errorCode = e.getErrorCode();
                    if (errorCode == EMError.NONETWORK_ERROR) {
                    } else if (errorCode == EMError.USER_ALREADY_EXISTS) {
                    } else if (errorCode == EMError.UNAUTHORIZED) {
                    } else if (errorCode == EMError.ILLEGAL_USER_NAME) {
                    } else {
                    }
                }

                if (mUser != null) {// 用户不为空
                    EMChatManager.getInstance().login(mUser.getUsername(), mUser.getPassword(), new EMCallBack() {

                        @Override
                        public void onSuccess() {
                          //  Toast.makeText(App.getAppContext(),"登录成功",Toast.LENGTH_SHORT).show();

//                        startVoiceCall();
                        }

                        @Override
                        public void onProgress(int progress, String status) {
                        }

                        @Override
                        public void onError(final int code, final String message) {
                           // Toast.makeText(App.getAppContext(),"服务器出错",Toast.LENGTH_SHORT).show();

                        }
                    });
                }
            }
        }).start();
    }


    /****
     * 退出登录
     * **/
    public static void logout() {
        EMChatManager.getInstance().logout(new EMCallBack() {

            @Override
            public void onSuccess() {
//                Toast.makeText(App.getAppContext(),"退出登录成功",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onProgress(int progress, String status) {

            }

            @Override
            public void onError(int code, String error) {
//                Toast.makeText(App.getAppContext(),"退出登录失败",Toast.LENGTH_SHORT).show();
            }
        });
    }


}
